﻿using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Conventions.Helpers;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using PlusAssistance.DAL.Mapping.Overrides;
using PlusAssistance.Domain;

namespace PlusAssistance.DAL.Concrete
{
    public class NHibernateConfig
    {
        private static Configuration _config;

        public static ISessionFactory SessionFactory { get; private set; }

        public static void Setup()
        {
            _config = null;
            var sessionFactory = Fluently.Configure()
               .Database(
                    MsSqlConfiguration.MsSql2008.ConnectionString(
                        connstr => connstr.FromConnectionStringWithKey("DatabaseConnectionString")))
                .Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<BaseEntity>()
                    .Conventions.Add(DefaultCascade.All())
                     .UseOverridesFromAssemblyOf<ClientOverride>()
                    ))
                .ExposeConfiguration(cfg => _config = cfg)
                .BuildSessionFactory();

            SessionFactory = sessionFactory;

            CreateDB();
        }

        private static void CreateDB()
        {
            new SchemaUpdate(_config).Execute(true, true);
            var session = SessionFactory.OpenSession();
        }
    }
}
